package com.atguigu.tingshu.account.listener;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Log4j2
public class UserAndAccountMessageListener {
    @Resource
    UserAccountService userAccountService;
    /**
     * 完成用户账户初始化操作
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(queues = "user_and_account_queue")
    public void userAndAccountMessageListenerTask(Channel channel, Message message){


        //获取消息
        Long userId = Long.valueOf(new String(message.getBody()));
        //获取消息属性
        MessageProperties properties = message.getMessageProperties();
        //获取消息编号：当前第几条消息
        long deliveryTag = properties.getDeliveryTag();
        try {
            //初始化账号
            userAccountService.initUserAccount(userId);
            //确认消息 1 消息编号 2 是否批量确认
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            //消费消息失败 重新消费
            if (properties.getRedelivered()) {
                //消息被拒绝过
                log.error("消息两次消费都失败用户id为"+userId+"失败原因为："+e.getMessage());
                //消息丢掉
                channel.basicReject(deliveryTag, false);
            } else {
                //消息没有被拒绝 1 消息编号 2 放回队列
                channel.basicReject(deliveryTag, true);
            }
        }
    }
}
